package cn.turboinfo.fuyang.api.provider.common.service.impl.sensitive;

import cn.turboinfo.fuyang.api.domain.common.service.sensitive.SensitiveWordService;
import cn.turboinfo.fuyang.api.entity.common.pojo.sensitive.SensitiveWord;
import cn.turboinfo.fuyang.api.provider.common.repository.database.sensitive.SensitiveWordDAO;
import cn.turboinfo.fuyang.api.provider.common.repository.database.sensitive.SensitiveWordPO;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.helper.service.impl.DefaultQServiceImpl;
import nxcloud.foundation.core.data.support.annotation.EnableSoftDelete;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hai
 */
@Slf4j
@RequiredArgsConstructor
@Service
@EnableSoftDelete
@Lazy
public class SensitiveWordServiceImpl extends DefaultQServiceImpl<SensitiveWord, Long, SensitiveWordPO, SensitiveWordDAO> implements SensitiveWordService {

    private SensitiveWordBs sensitiveWordBs;


    private SensitiveWordBs buildSensitiveWordBs() {

        return SensitiveWordBs.newInstance()
                .wordDeny(() -> dao.findAllByOrderById().stream()
                        .map(SensitiveWordPO::getWord)
                        .toList())
                .enableNumCheck(false)
                .init();
    }

    @Override
    public List<SensitiveWord> findAll() {
        return convertStreamQBeanToList(dao.findAllByOrderById().stream());
    }

    @Override
    public boolean containsDenyWords(String text) {
        if (null == sensitiveWordBs) {
            sensitiveWordBs = buildSensitiveWordBs();
        }
        return sensitiveWordBs.contains(text);
    }

    @Override
    public void refresh() {
        // 每次数据库的信息发生变化之后，首先调用更新数据库敏感词库的方法，然后调用这个方法。
        if (null == sensitiveWordBs) {
            sensitiveWordBs = buildSensitiveWordBs();
        }
        sensitiveWordBs
                .wordDeny(() -> dao.findAllByOrderById().stream()
                        .map(SensitiveWordPO::getWord)
                        .toList())
                .init();
    }

}
